<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>🏫 考勤记录管理系统</title>
    <link rel="stylesheet" href="static/elementui.css">
    <script src="static/vue@2.6.14.js"></script>
    <script src="static/elementui.js"></script>
    <script src="static/axios.min.js"></script>
    <style>
        body {
            padding: 20px;
            background-color: #f0f2f5;
            font-family: 'Arial', sans-serif;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .card-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }

        .attendance-card {
            transition: all 0.3s ease;
            background-color: #ffffff;
            border-radius: 12px;
            overflow: hidden;
        }

        .attendance-card:hover {
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
            transform: translateY(-10px);
        }

        .avatar-container {
            width: 200px;
            height: 200px;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 8px;
            overflow: hidden;
            margin: 10px auto;
        }

        .avatar {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    </style>
</head>
<body>
<div id="app">
    <el-card>
        <div class="toolbar">
            <el-input
                    placeholder="🔍 搜索考勤记录"
                    v-model="searchKeyword"
                    style="width: 250px;"
                    prefix-icon="el-icon-search">
            </el-input>
        </div>

        <div class="card-container">
            <el-card
                    v-for="record in filteredRecords"
                    :key="record.id"
                    class="attendance-card"
                    shadow="hover">
                <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="font-size: 18px; font-weight: bold;">
                        📋 考勤记录
                    </span>
                    <el-tag
                            :type="getStatusType(record.status)"
                            size="small">
                        {{ record.status || '未处理' }}
                    </el-tag>
                </div>
                <div class="card-body">
                    <p><strong>🕰️ 签到时间:</strong> {{ record.checkInTime || '未签到' }}</p>
                    <p><strong>⏳ 请假时间:</strong>
                        {{ record.startTime ? `${record.startTime} 至 ${record.endTime}` : '未请假' }}
                    </p>
                    <p><strong>📝 请假原因:</strong> {{ record.reason || '无' }}</p>

                    <div class="avatar-container">
                        <img v-if="record.recordImage" :src="record.recordImage" class="avatar" alt="记录图片"/>
                        <el-upload
                                v-else
                                class="avatar-uploader"
                                action="/upload"
                                :show-file-list="false"
                                :on-success="(res) => handleImageUpload(record, res)"
                                :before-upload="beforeImageUpload">
                            <i class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </div>
                <div class="card-footer" style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #909399; font-size: 12px;">
                        <strong>📅 创建时间:</strong> {{ record.createdAt }}
                    </span>
                    <div v-if="record.status === null || record.status === '未处理' || record.status === '未签到' || record.status === '正常'">
                        <el-button
                                type="primary"
                                size="small"
                                @click="handleCheckIn(record)">
                            ✅ 签到
                        </el-button>
                        <el-button
                                type="warning"
                                size="small"
                                @click="showLeaveDialog(record)">
                            🕊️ 请假
                        </el-button>
                    </div>
                    <div v-else-if="record.status === '签到过期' || record.status === '未签到'">
                        <el-button
                                type="danger"
                                size="small"
                                @click="handleReschedule(record)">
                            📝 申请补签
                        </el-button>
                    </div>
                </div>
            </el-card>
        </div>

        <el-dialog title="请假申请" :visible.sync="leaveDialogVisible" width="30%">
            <el-form :model="leaveForm" label-width="100px">
                <el-form-item label="请假原因">
                    <el-input v-model="leaveForm.reason" placeholder="请输入请假原因"></el-input>
                </el-form-item>
                <el-form-item label="开始时间">
                    <el-date-picker
                            v-model="leaveForm.startTime"
                            type="date"
                            placeholder="选择开始日期"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间">
                    <el-date-picker
                            v-model="leaveForm.endTime"
                            type="date"
                            placeholder="选择结束日期"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="leaveDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitLeaveRequest">确 定</el-button>
            </span>
        </el-dialog>

        <div class="block" style="margin-top: 20px; text-align: center;">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[5, 10, 20, 50]"
                    :page-size="pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalRecords">
            </el-pagination>
        </div>
    </el-card>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                searchKeyword: '',
                attendanceRecords: [],
                totalRecords: 0,
                pageSize: 5,
                currentPage: 1,
                user: {},
                leaveDialogVisible: false,
                currentRecord: null,
                leaveForm: {
                    reason: '',
                    startTime: '',
                    endTime: ''
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() < Date.now() - 8.64e7; // 不能选择今天之前的日期
                    }
                }
            };
        },
        computed: {
            filteredRecords() {
                return this.attendanceRecords.filter(record => {
                    return (record.recordType || '').includes(this.searchKeyword) ||
                        ((record.status || '未处理') || '').includes(this.searchKeyword) ||
                        (record.reason || '').includes(this.searchKeyword);
                });
            }
        },
        methods: {
            getStatusType(status) {
                if (!status) return 'info';
                switch (status) {
                    case '正常':
                    case '未签到':
                    case '未处理':
                        return 'info';
                    case '已签到':
                        return 'success';
                    case '请假':
                        return 'warning';
                    case '缺勤':
                        return 'danger';
                    default:
                        return 'info';
                }
            },
            fetchAttendanceRecords() {
                axios.get('/attendanceRecord?operation=findByStudentId', {
                    params: {
                        studentId: this.user.id,
                        pageNum: this.currentPage,
                        pageSize: this.pageSize
                    }
                }).then(response => {
                    const {code, msg, data} = response.data;
                    if (code === 200) {
                        this.attendanceRecords = data;
                        this.totalRecords = data.length;
                    } else {
                        this.$message.error(msg || '获取考勤记录失败 🚫');
                    }
                }).catch(error => {
                    console.error('获取考勤记录失败:', error);
                    this.$message.error('获取考勤记录失败 🚫');
                });
            },
            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchAttendanceRecords();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchAttendanceRecords();
            },
            handleCheckIn(record) {
                const updateData = {
                    id: record.id,
                    status: '已签到',
                    checkInTime: new Date().toISOString(),
                    studentId: record.studentId,
                    attendanceId: record.attendanceId
                };
                this.updateAttendanceRecord(updateData);
            },
            showLeaveDialog(record) {
                this.currentRecord = record;
                this.leaveDialogVisible = true;
                // 重置表单
                this.leaveForm = {
                    reason: '',
                    startTime: '',
                    endTime: ''
                };
            },
            submitLeaveRequest() {
                if (!this.leaveForm.reason) {
                    this.$message.warning('请输入请假原因 📝');
                    return;
                }
                if (!this.leaveForm.startTime) {
                    this.$message.warning('请选择开始时间 🕰️');
                    return;
                }
                if (!this.leaveForm.endTime) {
                    this.$message.warning('请选择结束时间 🕰️');
                    return;
                }

                const updateData = {
                    id: this.currentRecord.id,
                    status: '请假',
                    reason: this.leaveForm.reason,
                    startTime: new Date(this.leaveForm.startTime).toISOString(),
                    endTime: new Date(this.leaveForm.endTime).toISOString(),
                    studentId: this.currentRecord.studentId,
                    attendanceId: this.currentRecord.attendanceId
                };

                this.updateAttendanceRecord(updateData);
                this.leaveDialogVisible = false;
            },
            updateAttendanceRecord(updateData) {
                axios.post('/attendanceRecord?operation=update', updateData)
                    .then(response => {
                        const {code, msg} = response.data;
                        if (code === 200) {
                            this.$message.success(msg || '更新考勤记录成功 ✅');
                            this.fetchAttendanceRecords();
                        } else {
                            this.$message.error(msg || '更新考勤记录失败 🚫');
                        }
                    }).catch(error => {
                    console.error('更新考勤记录失败:', error);
                    this.$message.error('更新考勤记录失败 🚫');
                });
            },
            handleImageUpload(record, response) {
                // 处理图片上传成功的逻辑
                if (response.code === 200) {
                    const updateData = {
                        id: record.id,
                        recordImage: response.data,
                        studentId: record.studentId,
                        attendanceId: record.attendanceId
                    };
                    this.updateAttendanceRecord(updateData);
                } else {
                    this.$message.error('图片上传失败 🚫');
                }
            },
            beforeImageUpload(file) {
                return true;
            },
            handleReschedule(record) {
                const updateData = {
                    id: record.id,
                    status: '补签申请',
                    studentId: record.studentId,
                    attendanceId: record.attendanceId
                };
                this.updateAttendanceRecord(updateData);
            }
        },
        mounted() {
            const userData = localStorage.getItem('user');
            if (userData) {
                this.user = JSON.parse(userData);
            }
            this.fetchAttendanceRecords();
        }
    });
</script>
</body>
</html>